<template>

  <div class="table1_container1">
    <div class="table1_dataShower" style="padding-bottom: 50px; padding-top: 50px; box-sizing: border-box">
      <button class="report-top-button" @click="back">返回上级页面</button>

      <button class="report-top-button" @click="openFieldDialog">选择字段</button>
      <button class="report-top-button" @click="printReport">报表打印</button>
      <div style="text-align: center; margin: 10px 0;">
        <div style="display: inline-flex; gap: 20px;">
          <!-- 未完成 -->
          <div style="display: flex; align-items: center;">
            <div
              style="width: 16px; height: 16px; background-color: #ffffff; border: 1px solid #ddd; margin-right: 5px;"
            />
            <span>未完成</span>
          </div>

          <!-- 已完成 -->
          <div style="display: flex; align-items: center;">
            <div
              style="width: 16px; height: 16px; background-color: #e6f7e6; border: 1px solid #ddd; margin-right: 5px;"
            />
            <span>已完成</span>
          </div>

          <!-- 不合格重采 -->
          <div style="display: flex; align-items: center;">
            <div
              style="width: 16px; height: 16px; background-color: #ffebeb; border: 1px solid #ddd; margin-right: 5px;"
            />
            <span>不合格重采</span>
          </div>
        </div>
      </div>
      <h1>钢筋材质试验报告汇总表</h1>
      <div class="signature-content" style="margin-bottom: 10px;">
                <span>
                    工程名称：郑州市第二人民医院东院区改扩建项目眼科综合楼#学生宿舍
                </span>
        <span>
                    &nbsp;&nbsp;&nbsp;&nbsp;年&nbsp;&nbsp;&nbsp;&nbsp;月&nbsp;&nbsp;&nbsp;&nbsp;日
                </span>
        <span>共1页</span>
        <span>第1页</span>
      </div>
      <div class="table-scroll-wrapper">
        <table class="wendu-table1_top_table">
          <tr>
            <template v-for="field in tableHeaders">
              <template v-if="field.type === 'mechanicsGroup'">
                <td :key="field.key" rowspan="1" :colspan="field.colspan">力 学 性 能</td>
              </template>
              <template v-else-if="field.type === 'bendingGroup'">
                <td :key="field.key" rowspan="1" :colspan="field.colspan">弯 曲 性 能</td>
              </template>
              <template v-else>
                <td :key="field.key" :rowspan="field.rowspan || 2" :colspan="field.colspan || 1">{{ field.label }}</td>
              </template>
            </template>
          </tr>
          <tr>
            <template v-for="field in tableHeaders">
              <template v-if="field.type === 'mechanicsGroup'">
                <template v-if="isFieldVisible('yieldStrength1')">
                  <td :key="'yieldStrength-header'" colspan="2">屈服强度(MPa)</td>
                </template>
                <template v-if="isFieldVisible('pullStrength1')">
                  <td :key="'pullStrength-header'" colspan="2">抗拉强度(MPa)</td>
                </template>
                <template v-if="isFieldVisible('stretchRatio1')">
                  <td :key="'stretchRatio-header'" colspan="2">伸长率(%)</td>
                </template>
                <template v-if="isFieldVisible('totalStretchRatio1')">
                  <td :key="'totalStretchRatio-header'" colspan="2">总伸长率(%)</td>
                </template>
                <template v-if="isFieldVisible('qiangqubi1')">
                  <td :key="'qiangqubi-header'" colspan="2">强屈比</td>
                </template>
                <template v-if="isFieldVisible('chaoqubi1')">
                  <td :key="'chaoqubi-header'" colspan="2">屈标比</td>
                </template>
              </template>
              <template v-else-if="field.type === 'bendingGroup'">
                <template v-if="isFieldVisible('bendingDiameter1')">
                  <td :key="'bendingDiameter-header'" colspan="2">弯曲压头直径(mm)</td>
                </template>
                <template v-if="isFieldVisible('bendingAngle1')">
                  <td :key="'bendingAngle-header'" colspan="2">弯曲角度(°)</td>
                </template>
                <template v-if="isFieldVisible('bendingResult1')">
                  <td :key="'bendingResult-header'" colspan="2">结果</td>
                </template>
              </template>
            </template>
          </tr>
          <tr v-for="(item, index) in reportData" :key="index">
            <template v-for="field in tableHeaders">
              <template v-if="field.type === 'mechanicsGroup'">
                <template v-if="isFieldVisible('yieldStrength1')">
                  <td :key="'yieldStrength1-' + index">{{ item.yieldStrengths && item.yieldStrengths[0] }}</td>
                  <td :key="'yieldStrength2-' + index">{{ item.yieldStrengths && item.yieldStrengths[1] }}</td>
                </template>
                <template v-if="isFieldVisible('pullStrength1')">
                  <td :key="'pullStrength1-' + index">{{ item.pullStrengths && item.pullStrengths[0] }}</td>
                  <td :key="'pullStrength2-' + index">{{ item.pullStrengths && item.pullStrengths[1] }}</td>
                </template>
                <template v-if="isFieldVisible('stretchRatio1')">
                  <td :key="'stretchRatio1-' + index">{{ item.stretchRatios && item.stretchRatios[0] }}</td>
                  <td :key="'stretchRatio2-' + index">{{ item.stretchRatios && item.stretchRatios[1] }}</td>
                </template>
                <template v-if="isFieldVisible('totalStretchRatio1')">
                  <td :key="'totalStretchRatio1-' + index">{{
                      item.totalStretchRatios && item.totalStretchRatios[0]
                    }}
                  </td>
                  <td :key="'totalStretchRatio2-' + index">{{
                      item.totalStretchRatios && item.totalStretchRatios[1]
                    }}
                  </td>
                </template>
                <template v-if="isFieldVisible('qiangqubi1')">
                  <td :key="'qiangqubi1-' + index">{{ item.qiangqubis && item.qiangqubis[0] }}</td>
                  <td :key="'qiangqubi2-' + index">{{ item.qiangqubis && item.qiangqubis[1] }}</td>
                </template>
                <template v-if="isFieldVisible('chaoqubi1')">
                  <td :key="'chaoqubi1-' + index">{{ item.chaoqubis && item.chaoqubis[0] }}</td>
                  <td :key="'chaoqubi2-' + index">{{ item.chaoqubis && item.chaoqubis[1] }}</td>
                </template>
              </template>
              <template v-else-if="field.type === 'bendingGroup'">
                <template v-if="isFieldVisible('bendingDiameter1')">
                  <td :key="'bendingDiameter1-' + index">{{ item.bendingDiameters && item.bendingDiameters[0] }}</td>
                  <td :key="'bendingDiameter2-' + index">{{ item.bendingDiameters && item.bendingDiameters[1] }}</td>
                </template>
                <template v-if="isFieldVisible('bendingAngle1')">
                  <td :key="'bendingAngle1-' + index">{{ item.bendingAngles && item.bendingAngles[0] }}</td>
                  <td :key="'bendingAngle2-' + index">{{ item.bendingAngles && item.bendingAngles[1] }}</td>
                </template>
                <template v-if="isFieldVisible('bendingResult1')">
                  <td :key="'bendingResult1-' + index">{{ item.bendingResults && item.bendingResults[0] }}</td>
                  <td :key="'bendingResult2-' + index">{{ item.bendingResults && item.bendingResults[1] }}</td>
                </template>
              </template>
              <template v-else>
                <td :key="field.key + '-' + index" :colspan="field.colspan || 1">
                  {{ getFieldValue(item, field.key, index) }}
                </td>
              </template>
            </template>
          </tr>
        </table>
      </div>
      <div class="signature-content" style="margin-top: 20px;">
        <span>总监理工程师(建设单位项目技术负责人)：&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
        <span>（监理项目部章）&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
        <span>填表人：xxx</span>
      </div>
    </div>

    <!-- 字段选择对话框 -->
    <el-dialog
      title="选择显示字段"
      :visible.sync="fieldDialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <div style="max-height: 500px; overflow-y: auto;">
        <el-checkbox
          :indeterminate="isIndeterminate"
          v-model="checkAll"
          @change="handleCheckAllChange"
          style="margin-bottom: 15px;"
        >
          全选
        </el-checkbox>
        <el-divider></el-divider>
        <el-checkbox-group v-model="selectedFields" @change="handleCheckedFieldsChange" class="field-checkbox-group">
          <div
            v-for="field in allFields"
            :key="field.key"
            style="margin-bottom: 10px;"
          >
            <el-checkbox :label="field.key">{{ field.label }}</el-checkbox>
          </div>
        </el-checkbox-group>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmFieldSelection">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

/*
 *    这个报表真麻烦！！！
 *
 */

import { getSteelPreview } from '@/api/statementManage/wuZi/wuZi'
import item from '@/layout/components/Sidebar/Item.vue'

export default {
  computed: {
    item() {
      return item
    }
  },
  data() {
    return {
      localStorageId: '',
      reportData: {},
      previewData: {},
      projectName: '',
      subprojectName: '',
      // 字段选择相关
      fieldDialogVisible: false,
      checkAll: true,
      isIndeterminate: false,
      selectedFields: [], // 选中的字段key数组
      allFields: [ // 所有可用字段
        { key: 'dataId', label: '批次', colspan: 1 },
        { key: 'steelType', label: '钢筋种类', colspan: 2 },
        { key: 'producer', label: '生产厂家', colspan: 2 },
        { key: 'heatBatchNumber', label: '炉批号', colspan: 2 },
        { key: 'diameter', label: '公称直径', colspan: 2 },
        { key: 'antiQuakeLevel', label: '抗震等级', colspan: 2 },
        { key: 'getAmount', label: '进场批量', colspan: 2 },
        { key: 'batchAmount', label: '送检数量（组）', colspan: 2 },
        { key: 'useAmount', label: '本单位工程数量(吨)', colspan: 4 },
        { key: 'usePart', label: '使用部位', colspan: 2 },
        { key: 'representAmount', label: '本组试件代表数量（吨）', colspan: 4 },
        { key: 'fetchDate', label: '进场日期', colspan: 2 },
        { key: 'witnessDate', label: '见证日期', colspan: 2 },
        { key: 'checkDate', label: '送样日期', colspan: 2 },
        { key: 'reportDate', label: '报告日期', colspan: 2 },
        { key: 'reportNumber', label: '试验报告编号', colspan: 2 },
        { key: 'weightDeviation', label: '重量偏差(%)', colspan: 2 },
        { key: 'mechanicsGroup', label: '力学性能', type: 'mechanicsGroup', colspan: 12 },
        { key: 'bendingGroup', label: '弯曲性能', type: 'bendingGroup', colspan: 6 },
        { key: 'conclusion', label: '结论', colspan: 2 },
        { key: 'projectName', label: '项目名称', colspan: 2 },
        { key: 'subprojectName', label: '单位工程(栋)', colspan: 2 },
        { key: 'primaryKey', label: '主键', colspan: 1 },
        { key: 'yanshouRule', label: '验收规范', colspan: 1 },
        { key: 'projectNumber', label: '工程号', colspan: 1 },
        { key: 'superviseNumber', label: '监督号', colspan: 1 },
        { key: 'checkCompany', label: '检测单位', colspan: 1 },
        { key: 'delegateCompany', label: '委托单位', colspan: 1 },
        { key: 'delegateNumber', label: '委托编号', colspan: 1 },
        { key: 'witnessCompany', label: '见证单位', colspan: 1 },
        { key: 'witnessPerson', label: '见证人', colspan: 1 },
        { key: 'sendPerson', label: '送样人', colspan: 1 },
        { key: 'checkType', label: '检验类别', colspan: 1 },
        { key: 'jiansheCompany', label: '建设单位', colspan: 1 },
        { key: 'shigongCompany', label: '施工单位', colspan: 1 },
        // 力学性能子字段
        { key: 'yieldStrength1', label: '屈服强度(MPa)', colspan: 2, parent: 'mechanicsGroup' },
        { key: 'pullStrength1', label: '抗拉强度(MPa)', colspan: 2, parent: 'mechanicsGroup' },
        { key: 'stretchRatio1', label: '伸长率(%)', colspan: 2, parent: 'mechanicsGroup' },
        { key: 'totalStretchRatio1', label: '总伸长率(%)', colspan: 2, parent: 'mechanicsGroup' },
        { key: 'qiangqubi1', label: '强屈比', colspan: 2, parent: 'mechanicsGroup' },
        { key: 'chaoqubi1', label: '屈标比', colspan: 2, parent: 'mechanicsGroup' },
        // 弯曲性能子字段
        { key: 'bendingDiameter1', label: '弯曲压头直径(mm)', colspan: 2, parent: 'bendingGroup' },
        { key: 'bendingAngle1', label: '弯曲角度(°)', colspan: 2, parent: 'bendingGroup' },
        { key: 'bendingResult1', label: '结果', colspan: 2, parent: 'bendingGroup' }
      ]
    }
  },
  computed: {
    // 生成表头结构
    tableHeaders() {
      const headers = []
      const mechanicsFields = ['yieldStrength1', 'pullStrength1', 'stretchRatio1', 'totalStretchRatio1', 'qiangqubi1', 'chaoqubi1']
      const bendingFields = ['bendingDiameter1', 'bendingAngle1', 'bendingResult1']
      const selectedMechanicsFields = this.selectedFields.filter(k => mechanicsFields.includes(k))
      const selectedBendingFields = this.selectedFields.filter(k => bendingFields.includes(k))

      // 按原始顺序遍历所有字段
      let mechanicsGroupAdded = false
      let bendingGroupAdded = false

      this.allFields.forEach(field => {
        // 跳过子字段，它们会在组中处理
        if (field.parent) {
          return
        }

        if (this.selectedFields.includes(field.key)) {
          // 处理力学性能组合字段
          if (field.key === 'mechanicsGroup') {
            if (!mechanicsGroupAdded && selectedMechanicsFields.length > 0) {
              headers.push({
                key: 'mechanicsGroup',
                type: 'mechanicsGroup',
                label: '力 学 性 能',
                colspan: selectedMechanicsFields.length * 2
              })
              mechanicsGroupAdded = true
            }
          }
          // 处理弯曲性能组合字段
          else if (field.key === 'bendingGroup') {
            if (!bendingGroupAdded && selectedBendingFields.length > 0) {
              headers.push({
                key: 'bendingGroup',
                type: 'bendingGroup',
                label: '弯 曲 性 能',
                colspan: selectedBendingFields.length * 2
              })
              bendingGroupAdded = true
            }
          }
          // 普通字段
          else {
            headers.push({
              key: field.key,
              type: 'normal',
              label: field.label,
              colspan: field.colspan || 1,
              rowspan: field.rowspan || 2
            })
          }
        }
      })

      return headers
    }
  },
  async mounted() { // 钩子函数
    const sessionData = sessionStorage.getItem('tempObj1')

    const parseData = JSON.parse(sessionData)
    this.projectName = parseData.projectName
    this.subprojectName = parseData.subprojectName
    const subprojectId = parseData.subprojectId

    const { result } = await getSteelPreview(subprojectId)

    this.reportData = result

    // 初始化字段选择（默认全选）
    this.selectedFields = this.allFields.filter(f => !f.parent).map(f => f.key)
    // 默认选中所有力学性能和弯曲性能子字段
    this.selectedFields.push('yieldStrength1', 'pullStrength1', 'stretchRatio1', 'totalStretchRatio1', 'qiangqubi1', 'chaoqubi1')
    this.selectedFields.push('bendingDiameter1', 'bendingAngle1', 'bendingResult1')
    this.checkAll = true
    this.isIndeterminate = false
  },
  beforeDestroy() { // 离开页面要做的事
    // 那就是清除localstorage！！！
    if (this.localStorageId) {
      localStorage.removeItem(this.localStorageId)
    }
    document.querySelector('body').setAttribute('style', 'background-color: white;') // 还原，因为这是个全局样式
  },
  beforeCreate() {
    document.querySelector('body').setAttribute('style', 'background-color:#f5f5f5;') // 设置对比色
  },
  methods: {
    back() {
      // 使用 go(-1) 返回上一页
      this.$router.go(-1)
    },
    // 打开字段选择对话框
    openFieldDialog() {
      this.fieldDialogVisible = true
    },
    // 全选/取消全选
    handleCheckAllChange(val) {
      if (val) {
        // 全选：选中所有非子字段
        this.selectedFields = this.allFields.filter(f => !f.parent).map(f => f.key)
        // 如果选中了力学性能组，默认选中所有力学性能子字段
        if (this.selectedFields.includes('mechanicsGroup')) {
          this.selectedFields.push('yieldStrength1', 'pullStrength1', 'stretchRatio1', 'totalStretchRatio1', 'qiangqubi1', 'chaoqubi1')
        }
        // 如果选中了弯曲性能组，默认选中所有弯曲性能子字段
        if (this.selectedFields.includes('bendingGroup')) {
          this.selectedFields.push('bendingDiameter1', 'bendingAngle1', 'bendingResult1')
        }
      } else {
        this.selectedFields = []
      }
      this.isIndeterminate = false
    },
    // 字段选择变化时更新全选状态
    handleCheckedFieldsChange(value) {
      const nonParentFields = this.allFields.filter(f => !f.parent)
      const checkedNonParentCount = value.filter(k => nonParentFields.some(f => f.key === k)).length
      this.checkAll = checkedNonParentCount === nonParentFields.length
      this.isIndeterminate = checkedNonParentCount > 0 && checkedNonParentCount < nonParentFields.length
    },
    // 确认字段选择
    confirmFieldSelection() {
      // 检查是否至少选择了一个字段
      const nonParentFields = this.selectedFields.filter(k => this.allFields.find(f => f.key === k && !f.parent))
      if (nonParentFields.length === 0) {
        this.$message.warning('请至少选择一个字段！')
        return
      }
      this.fieldDialogVisible = false
      this.$message.success('字段选择已更新！')
    },
    // 判断字段是否可见（用于力学性能和弯曲性能的子字段显示）
    isFieldVisible(fieldKey) {
      return this.selectedFields.includes(fieldKey)
    },
    // 根据字段key获取对应的值
    getFieldValue(item, fieldKey, index) {
      const valueMap = {
        'dataId': item.dataId,
        'steelType': item.steelType,
        'producer': item.producer,
        'heatBatchNumber': item.heatBatchNumber,
        'diameter': item.diameter,
        'antiQuakeLevel': item.antiQuakeLevel,
        'getAmount': item.getAmount,
        'batchAmount': item.batchAmount,
        'useAmount': item.useAmount,
        'usePart': item.usePart,
        'representAmount': item.representAmount,
        'fetchDate': item.fetchDate,
        'witnessDate': item.witnessDate,
        'checkDate': item.checkDate,
        'reportDate': item.reportDate,
        'reportNumber': item.reportNumber,
        'weightDeviation': item.weightDeviation,
        'conclusion': item.conclusion,
        'projectName': this.projectName,
        'subprojectName': this.subprojectName,
        'primaryKey': item.dataId,
        'yanshouRule': item.yanshouRule,
        'projectNumber': item.projectNumber,
        'superviseNumber': item.superviseNumber,
        'checkCompany': item.checkCompany,
        'delegateCompany': item.delegateCompany,
        'delegateNumber': item.delegateNumber,
        'witnessCompany': item.witnessCompany,
        'witnessPerson': item.witnessPerson,
        'sendPerson': item.sendPerson,
        'checkType': item.checkType,
        'jiansheCompany': item.jiansheCompany,
        'shigongCompany': item.shigongCompany
      }
      return valueMap[fieldKey] || ''
    },
    // 打印报表
    printReport() {
      window.print()
    }
  }
}
</script>

<style>
/*
先来设置每个任务项对应的背景颜色吧！
 */
.row-unfinished {
  background-color: #ffffff;
  /* 未完成 - 白色或默认色 */
}

.row-finished {
  background-color: #e6f7e6;
  /* 已完成 - 浅绿色 */
}

.row-failed {
  background-color: #ffebeb;
  /* 不合格重采 - 浅红色 */
}

.table1_container1 {
  width: 6000px;
  background: white;
  margin-left: auto;
  margin-right: auto;
  text-align: center;
  padding-bottom: 20px;
}

.table1_dataShower {
  padding-left: 2%;
  padding-right: 2%;
  width: 80%;
  background: white;
  margin: 0 auto;
  border: 2px black solid;
}

.table-scroll-wrapper {
  width: 100%;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
}

.wendu-table1_top_table {
  width: max-content;
  /* 按内容撑开 */
  min-width: 100%;
  /* 在宽屏时至少填满容器 */
  margin: 0;
  /* 不需要 auto 居中，scroll wrapper 决定显示 */
  table-layout: auto;
  /* 根据内容决定列宽 */
}

/*这是返回按钮的样式*/
.report-top-button {
  display: block;
  margin: 0 auto;
  margin-bottom: 20px;
  padding: 12px 28px;
  font-size: 16px;
  font-weight: 600;
  font-family: 'Arial', sans-serif;
  color: #ffffff;
  background: linear-gradient(90deg, #1e3a8a, #3b82f6);
  /* 建筑行业蓝色调，稳重且有活力 */
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.report-top-button:hover {
  background: linear-gradient(90deg, #1e3a8a, #2563eb);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
  transform: translateY(-1px);
}

.report-top-button:active {
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  transform: translateY(0);
}

/*表格样式*/
.wendu-table1_top_table {
  width: max-content;
  margin: 0 auto;
  border-collapse: collapse;
  border: 1px solid black;
  table-layout: fixed;
}

/*表格的样式*/
.wendu-table1_top_table tr td {
  height: 50px;
  border: 1px solid black;
  word-wrap: break-word;
  /* 允许长单词换行 */
  overflow-wrap: break-word;
  /* 更现代的换行属性 */
}

#table1_top_table_last_col {
  width: 20%;
  min-height: 50px;
}

th {
  box-sizing: border-box !important;
}

.signature-content {
  display: flex;
  align-items: center;
  /* 垂直居中对齐（可选） */
  justify-content: space-between;
  /* 左右两端对齐 */
  gap: 12px;
  /* 子项间距，可选 */
  width: 100%;
}

@media print {
  @page {
    size: A4 landscape;
    margin: 0.5in;
  }

  .table1_container1 {
    width: 100% !important;
    margin: 0 0 !important;
    border: none !important;
  }

  .table1_dataShower {
    width: 100% !important;
    margin: 0 0 !important;
    box-sizing: border-box !important;
    border: none !important;
    font-size: 7px;
  }

  .report-top-button {
    display: none !important;
  }

  /* 隐藏图例 */
  .table1_dataShower > div:not(.signature-content):not(.table-scroll-wrapper) {
    display: none !important;
  }

  .table-scroll-wrapper {
    width: 100% !important;
    overflow: visible !important;
  }

  .wendu-table1_top_table {
    width: 100% !important;
    font-size: 8px !important;
  }

  .wendu-table1_top_table tr td {
    height: 40px !important;
    font-size: 8px !important;
    padding: 2px !important;
  }

  h1 {
    font-size: 18px !important;
  }

  .signature-content {
    font-size: 12px !important;
  }
}

/* 字段选择对话框样式 */
.field-checkbox-group {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
</style>
